<template>
  <article class="page page-rtsp-player-canvas">
    <h4 class="text-center">RTSP播放器(canvas)</h4>
    <div class="page-body row">
      <div class="col-4">
        <fieldset>
          <legend>参数配置</legend>
          <div class="fieldset-content">
						<div class="alert alert-info">
							本工具基于ffmpeg，需要先行安装ffmpeg，并加入到环境变量。
						</div>
						<div class="form-group row-flex" align="center">
							<div class="row-flex-prefix">RTSP地址</div>
							<div class="row-flex-main"><input class="form-control" type="text" v-model.trim="videoUrl"
									placeholder="请输入播放地址" /></div>
						</div>
						<div class="form-group row-flex" align="center">
							<div class="row-flex-prefix">WS端口</div>
							<div class="row-flex-main"><input class="form-control" type="number" v-model.trim="wsPort"
									placeholder="WebSocket服务端口" /></div>
						</div>
						<!-- <div class="form-group row-flex" align="center">
							<div class="row-flex-prefix">画布尺寸</div>
							<div class="row-flex-main">
                <input class="form-control" type="text" v-model="cvsSize" placeholder="画布尺寸" readonly />
              </div>
              <div class="row-flex-suffix"><x-button size="small" @click="checkCvsSize">校正</x-button></div>
						</div> -->
						<div class="form-group row-flex" align="center">
							<div class="row-flex-prefix">画布宽度</div>
							<div class="row-flex-main">
                <input class="form-control" type="number" :min="10" v-model="cvsWidth" placeholder="画布宽度" />
              </div>
						</div>
						<div class="form-group row-flex" align="center">
							<div class="row-flex-prefix">画布高度</div>
							<div class="row-flex-main">
                <input class="form-control" type="number" :min="10" v-model="cvsHeight" placeholder="画布高度" />
              </div>
						</div>
						<div class="form-group row-flex" align="center">
							<div class="row-flex-prefix">FFmpeg</div>
							<div class="row-flex-main">
								<input class="form-control form-control-sm" type="text" v-model="ffmpegPath" placeholder="ffmpeg路径" readonly />
							</div>
							<div class="row-flex-suffix"><x-button size="small" @click="setPath">选择...</x-button></div>
						</div>
						<div class="form-group form-group-main"></div>
            <div class="form-group">
              <x-button type="primary" block @click="clickHandler">{{ loadingCount > 0 ? '停 止' : '播 放'}}</x-button>
            </div>
          </div>
        </fieldset>
      </div>
      <div class="col-8">
        <fieldset>
          <legend>播放区域</legend>
          <div class="fieldset-content canvas-wrapper" ref="canvasWrapper">
            <canvas ref="canvas" :id="id" :width="cvsWidth" :height="cvsHeight"></canvas>
          </div>
        </fieldset>
      </div>
    </div>
  </article>
</template>

<script>
const {remote} = global.require('electron')
const {dialog} = remote
const selfWindow= remote.getCurrentWindow()
let JSMpeg = global.JSMpeg || null
let nodeRtspStream = global.nodeRtspStream || null

export default {
  name: 'rtsp-player-canvas',
  data() {
    return {
			id: 'player_' + `${Math.random()}`.substring(2),
			streamServer: null,
			cvsPlayer: null,
      videoUrl: '',
      wsPort: 1104,
      cvsSize: '',
      cvsWidth: 100,
      cvsHeight: 100,
      message: '',
      ffmpegPath: 'ffmpeg',
      loadingCount: 0
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    init () {
      if (!this.$refs.canvasWrapper) return
      let info = this.$refs.canvasWrapper.getBoundingClientRect()
      this.cvsWidth = Math.floor(info.width)
      this.cvsHeight = Math.floor(info.height)
      this.cvsSize = `${this.cvsWidth}*${this.cvsHeight}`
    },
    // 设置ffmpeg文件路径
    setPath () {
      let filePaths = dialog.showOpenDialogSync(selfWindow, {
        title: '选择文件',
        buttonLabel:'确定',
        defaultPath: this.$sharedObject('desktopPath'),
        properties: ['openFile']
      })
      if (filePaths instanceof Array && filePaths.length > 0) {
        this.ffmpegPath = filePaths[0]
      }
    },
    // 点击按钮
    clickHandler() {
      if (this.loadingCount > 0) {
        this.playStop()
      } else {
        this.playStart()
      }
    },
    // 开始
    playStart() {
      if (!this.videoUrl) { return this.$toast('请输入视频地址') }
			if (!this.$refs.canvas) return
			// if (!document.getElementById(this.id)) return
			if (!JSMpeg) return
			this.loadingCount = 1
      this.streamServer = new nodeRtspStream({
        name: 'rtsp2Canvas',
        streamUrl: this.videoUrl,
        wsPort: this.wsPort,
        ffmpegOptions: { // options ffmpeg flags
          '-stats': '', // an option with no neccessary value uses a blank string
          '-r': 30 // options with required values specify the value after the key
        }
      })
      this.cvsPlayer = new JSMpeg.Player(`ws://localhost:${this.wsPort}`, {
        canvas: this.$refs.canvas,
        // canvas: document.getElementById(this.id), // Canvas should be a canvas DOM element
        autoplay: true
      })
      this.cvsPlayer.play()
    },
    // 结束
    playStop() {
			this.loadingCount = 0
      this.streamServer.stop()
      this.cvsPlayer.stop()
      this.cvsPlayer.destroy()
    },
    checkCvsSize () {
      let cvsObj = document.querySelector(`#${this.id}`)
      if (!cvsObj) return
      let cvsWrapperInfo = this.$refs.canvasWrapper.getBoundingClientRect()
      let cvsRate = cvsObj.width / cvsObj.height
      if (cvsRate > (cvsWrapperInfo.width / cvsWrapperInfo.height)) {
        this.cvsWidth = Math.floor(cvsWrapperInfo.width)
        this.cvsHeight = Math.floor(cvsWrapperInfo.width / cvsRate)
      } else {
        this.cvsWidth = Math.floor(cvsWrapperInfo.height * cvsRate)
        this.cvsHeight = Math.floor(cvsWrapperInfo.height)
      }
      this.cvsSize = `${this.cvsWidth}*${this.cvsHeight}`
    }
  }
}
</script>

<style scoped lang="less">
@import "~@/assets/css/_mixins.less";
@import "~@/assets/css/_color.less";

.page-rtsp-player-canvas {
  display: flex;
  flex-direction: column;

  .row-flex {
    &+.row-flex {
      margin-top: 1em;
    }

    .row-flex-prefix {
      min-width: 5em;
      text-align: right;
    }

    .row-flex-main {
      text-align: left;
    }
  }

  .page-body {
    height: 0;
    flex-grow: 1;
    overflow: hidden;
    position: relative;

    fieldset {
      height: 100%;
    }

    .fieldset-content {
      height: calc(100% - 2em);
      display: flex;
      flex-direction: column;
			position: relative;
			.form-group-main {
				flex-grow: 1;
			}
      canvas {
        .absolute-fullscreen;
        width: 100%;
        margin: auto;
        background-color: rgba(255, 255, 255, .5);
      }
    }
  }
}
</style>
